import os
import time
import webbrowser
from obs import *
from openstack import connection
from datetime import datetime
import configparser

def get_conf(path):
    conf = configparser.ConfigParser()
    conf.read(path)
    ram = conf.items("ram")
    return ram[0][1],ram[1][1]

def get_filelist(path):
    Filelist = []
    for home, dirs, files in os.walk(path):
        for filename in files:
            Filelist.append(os.path.join(home, filename)[5:])
    return Filelist

def del_bucket_file(obsClient,bucketName):
    keys = []
    resp = obsClient.listObjects(bucketName)
    for content in resp.body.contents:
        keys.append(Object(key=content.key))
    if len(keys)>0:
        resp = obsClient.deleteObjects(bucketName, DeleteObjectsRequest(False, keys))
        print('Delete from %s'%bucketName)
        if resp.body.deleted:
            for delete in resp.body.deleted:
                print('\tDelete：' + delete.key)
        if resp.body.error:
            for err in resp.body.error:
                print('\tError:' + str(err))
    else:
        print("can't find any file in %s"%bucketName)

def up_to_bucket(obsClient,bucketName,loc_path,Filelist):
    num = 0
    for file in Filelist :
        try:
            resp = obsClient.putFile(bucketName, file.replace('\\','/') , file_path=os.path.join(loc_path,file))
            if resp.status < 300: 
                # print('requestId:', resp.requestId,'etag:', resp.body.etag) 
                print('\tUpload:'+file)
                num+=1
        except :
            pass
    if num == len(Filelist):
        print('全部%d个文件上传成功！'%len(Filelist))
    else:
        print('有%d Upload failed！'%(len(Filelist)-num))

def refresh_cdn(conn,**refresh_file_task):
    try:
        task = conn.cdn.create_refresh_task(**refresh_file_task)
        print('Refresh CDN')
    except:
        print('Refresh CDN failed')

def main():
    AK = ""
    SK = ""
    bucketName = 'eegs.cn'
    AK, SK = get_conf('conf.ini')
    loc_path ='site'
    site_url = 'https://eegs.cn/'

    obsClient = ObsClient(access_key_id = AK, secret_access_key = SK, server = 'https://obs.cn-north-1.myhuaweicloud.com' )
    conn = connection.Connection(cloud= 'myhuaweicloud.com', ak=AK, sk=SK )
    os.environ.setdefault('OS_CDN_ENDPOINT_OVERRIDE', 'https://cdn.myhuaweicloud.com/v1.0/')

    refresh_file_task = {
        "type": "directory",  #file or directory file只刷新一部分，directory全部刷新
        "urls": [site_url]    # url在网页操作刷新CND执行成功，所以url没有问题
        }

    Filelist = get_filelist(loc_path)           #获取本地文件列表
    del_bucket_file(obsClient,bucketName)       #删除obs中文件
    up_to_bucket(obsClient,bucketName,loc_path,Filelist) #上传文件
    refresh_cdn(conn,**refresh_file_task)       #刷新cdn

    webbrowser.open(site_url)
    print('处理完成5s后退出。。。。。。')
    time.sleep(5)

if __name__ == '__main__':
    main()

